package com.review.Test;

import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.PriorityBlockingQueue;

public class MyPriorityBlockingQueue{



	public static void main(String[] args) throws InterruptedException {

		//testQueue();
		//testSet();
		
		//验证是否为阻塞queue，先取，5s后添加元素，结果能取走------说明是阻塞queue
		//testBlock();
		//testBlock2();
		//testBlock3();
	}

	private static void testBlock3() {
		//非阻塞queue：取元素时，若queue为空，则取出元素的值为null
		ConcurrentLinkedDeque<String> q = new ConcurrentLinkedDeque<>();
		System.out.println("取前");
		String peek = q.peek();
		System.out.println("取后");
		System.out.println(peek);
	}

	private static void testBlock2() throws InterruptedException {
		PriorityBlockingQueue<Person> q = new PriorityBlockingQueue<>();
		System.out.println("取前");
		Person person = q.take();
		System.out.println("取后");
		System.out.println(person);
	}

	private static void testBlock() throws InterruptedException {
		final PriorityBlockingQueue<Person> q = new PriorityBlockingQueue<>();
		
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				q.add(new Person("a", 1));
				System.out.println("添加成功");
			}
		},"添加");

		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Person person = q.take();
					System.out.println(person);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		},"取走");
		t2.start();
		Thread.sleep(3000);
		t1.start();
	}

	private static void testSet() {
		TreeSet<Person> set = new TreeSet<>();
		set.add(new Person("a", 1));
		set.add(new Person("a", 1));
		set.add(new Person("a", 4));
		set.add(new Person("b", 2));
		set.add(new Person("c", 3));

		System.out.println(set);
	}

	private static void testQueue() {
		PriorityBlockingQueue<Person> q = new PriorityBlockingQueue<>();
		q.add(new Person("a", 1));
		q.add(new Person("a", 1));
		q.add(new Person("a", 4));
		q.add(new Person("b", 2));
		q.add(new Person("c", 3));

		System.out.println(q);

		System.out.println(q.poll());
		System.out.println(q.poll());
		System.out.println(q.poll());
		System.out.println(q.poll());
		System.out.println(q);
	}


}
